<template>
  <div class="TabStatements">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 170px; margin-right: 2px;">
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="单据号" value="billCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户地址" value="csmAddress" />
        </el-select>
        <el-input v-model.trim="csmText" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="排序:">
        <el-select v-model="query.orderBy" clearable class="mr10">
          <el-option label="按制单日期" :value="0" />
          <el-option label="按账单截至日期" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 140px;" class="mr20">
          <el-option label="制单日期" :value="1" />
          <el-option label="销单日期" :value="2" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.billStatus" clearable placeholder="请选择">
          <el-option label="待核销" :value="1" />
          <el-option label="已结转" :value="2" />
          <el-option label="已销单" :value="3" />
          <el-option label="已作废" :value="4" />
          <el-option label="已审核" :value="5" />
          <el-option label="待销单" :value="30" />
          <el-option label="已驳回" :value="40" />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button v-permission="[90304, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div class="mb20">
      <el-button
        v-permission="[90304, 2]"
        type="primary"
        icon="el-icon-download"
        @click="exportFile"
      >导出</el-button>
    </div>
    <!-- 表格内容 -->
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      @fetch="fetchData"
    />
    <OrderDetailDialog ref="OrderDetailDialogRef" :tree-data="treeData" @refresh="search" />
  </div>
</template>

<script>
  import {
    queryExportDomain,
    queryMonthAccCsmMonthlyBillTableList,
    queryCsmTypeMap,
    monthAccCsmMonthlyTrackTabStatementsExport
  } from '@/api'
  import { formatFixed2, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import OrderDetailDialog from './components/OrderDetailDialog.vue'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import moment from 'dayjs'
  export default {
    name: 'tab-track',
    components: {
      OrderDetailDialog
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        customerTypeMap: [],
        rowData: {}, // 表格当前行数据
        date: [moment().date(1), new Date()], // 日期  最多支持一年的查询
        dateType: 1,
        csmText: '',
        csmType: 'csmPhone',
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          billStatus: '',
          orderBy: 1 // 排序方式
        },
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        },
        exportDomain: ''
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            prop: 'billCode',
            label: '单据号',
            width: 200,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>
              {row.billCode}
            </el-link>
          )
          },
          {
            prop: 'billStatus',
            label: '单据状态',
            width: 100,
            render: (h, { row }) => <span>{this.billStatusText(row.billStatus)}</span>
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmPhone',
            width: 110,
            label: '联系方式'
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 150
          },
          {
            prop: 'receivables',
            label: '应收金额',
            width: 100,
            align: 'right',
            formatter: row => formatFixed2(row.receivables)
          },
          {
            prop: 'payments',
            label: '核销金额',
            width: 100,
            align: 'right',
            formatter: row => formatFixed2(row.payments)
          },
          {
            prop: 'orgName',
            width: 150,
            label: '制单机构'
          },
          {
            prop: 'operator',
            // align: 'right',
            width: 150,
            label: '制单人'
          },
          {
            prop: 'createTime',
            width: 160,
            label: '制单日期',
            render: (h, { row }) => (
            <span>
              {row.createTime && parseTime(row.createTime, '{y}-{m}-{d}')}
            </span>
          )
          },
          {
            prop: 'endDt',
            width: 160,
            label: '本期账单截至日期',
            render: (h, { row }) => (
            <span>
              {row.endDt && parseTime(row.endDt, '{y}-{m}-{d}')}
            </span>
          )
          },
          {
            prop: 'auditTime',
            width: 160,
            label: '销单日期',
            render: (h, { row }) => (
            <span>{row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d}')}</span>
          )
          }
        ]
      }
    },
    created() {
      this.getTreeData()
      this.getCustomerTypeMap()
      this.getExportDomain()
    },
    methods: {
      // 获取客户类型方法
      async getCustomerTypeMap() {
        const res = await queryCsmTypeMap()
        this.customerTypeMap = res.data
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      billStatusText(val) {
        switch (val) {
        case 1:
          return '待核销'
        case 2:
          return '已结转'
        case 3:
          return '已销单'
        case 4:
          return '已作废'
        case 5:
          return '已审核'
        case 30:
          return '待销单'
        case 40:
          return '已驳回'
        }
      },

      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.csmText) query[this.csmType] = this.csmText
        if (this.date && this.date.length > 0) {
          query[`${this.dateType === 1 ? 'createTime' : 'auditTime'}`] = this.date[0]
          query[`${this.dateType === 1 ? 'createTimeEnd' : 'auditTimeEnd'}`] = this.date[1]
        }
        const res = await queryMonthAccCsmMonthlyBillTableList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      openDetail(row) {
        this.$refs['OrderDetailDialogRef'].show(3, row)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          monthAccCsmMonthlyTrackTabStatementsExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.TabStatements {
  .el-form-item .el-form-item {
    margin-bottom: 0;
  }

  .merge-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
}
</style>
